<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<%@ taglib prefix="his_fns" uri="/WEB-INF/tlds/his_fns.tld" %>

<div class="app">
    <section class="layout">
        <section class="main-content col-lg-12" id="drugInOutDiv">
            <div class="content-wrap">
                <div class="wrapper" style="bottom: 50px;">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#" onclick="loadDiv('mainCenterDiv','${ctx}/drug/drugStock/drugInOutIndex')">对消入出库</a>
                        </li>
                    </ul>
                    <section class="panel panel-default">
                        <div class="panel-body">
                            <div class="table-responsive no-border">
                                <div class="datatable-top">
                                    <div class="pull-left">
                                        <form:form id="searchForm" modelAttribute="drugStock"
                                                   onsubmit="return loadDivForm('mainCenterDiv','searchForm','${ctx}/drug/drugStock/drugInOutIndex');"
                                                   method="post" class="form-inline">
                                            <div class="form-group">
                                                <label class=" control-label">入库类别：</label>
                                                <form:select path="drugInoutClass.type" id="masterClassId" htmlEscape="false" class="form-control" maxlength="1" data-parsley-required="true">
                                                    <form:options items="${fns:getDictList('DRUG_STOTARG_TYPE')}" itemLabel="label" itemValue="label" htmlEscape="false" />
                                                </form:select>
                                            </div>

                                            <%--<div class="form-group">--%>
                                            <%--<label class=" control-label">日期：</label>--%>
                                            <%--<input name="startDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" value='<fmt:formatDate value="${drugPrice.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>'/>--%>
                                            <%--</div>--%>
                                            <div class="form-group">
                                                <label class=" control-label">供货单位：</label>
                                                <form:input path="supplier" id="supplier" htmlEscape="false" class="form-control"  maxlength="64"  />
                                                <form:hidden path="storageFrom"/>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">日期：</label>
                                                <input name="exportDate" id="expireDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly/>
                                            </div>
                                            <div class="form-group">
                                                <input id="btnSubmit" class="btn btn-primary" type="button" onclick="saveImport()" value="保存"/>
                                                <input id="addDrug" class="btn btn-primary" type="button" value="增加" onclick="addDrugList()"/>
                                            </div>
                                            <br/><br/>
                                            <div class="form-group">
                                                <label class=" control-label">出库类别：</label>
                                                <form:select path="drugInoutNewClass.type" id="masterClass" htmlEscape="false" class="form-control" maxlength="1" data-parsley-required="true"
                                                             onchange="loadSupplier()">
                                                    <form:options items="${his_fns:getExportClassDictList()}" itemLabel="label" itemValue="label" htmlEscape="false" />
                                                </form:select>
                                            </div>


                                            <div class="form-group">
                                                <label class=" control-label">收货科室：</label>
                                                <select class="form-control" id="supplierOut"></select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">合计：</label>
                                                <input class="form-control" id="totalMoney" type="text" readonly>
                                            </div>

                                        </form:form>
                                    </div>
                                </div>
                                <table id="contentTable" class="table table-bordered table-striped mg-t datatable">
                                    <thead>
                                    <tr>
                                        <th hidden>jsonText</th>
                                        <th >药品编码</th>
                                        <th>药品名称</th>
                                        <th>包装数量</th>
                                        <th>包装规格</th>
                                        <th>包装单位</th>
                                       <%-- <th>最小规格</th>
                                        <th>最小单位</th>--%>
                                        <th>厂家</th>
                                        <th>进价</th>
                                        <%--<th>售价</th>--%>
                                        <%--  <th>折扣</th>--%>
                                        <th>批号</th>
                                        <th>有效期</th>
                                        <th>数量(大包装)</th>
                                        <%--<th>出库数量(大包装)</th>
                                        <th>当前库存</th>--%>
                                        <%--<th>入库单号</th>--%>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>

        <%--右侧药品规格字典列表--%>
        <section class="main-content col-lg-4" style="display: none" id="drugInOutRightDiv">
            <div class="content-wrap" id="rigthCenterDiv">
            </div>
        </section>
    </section>
</div>
<script type="text/javascript">

    /*供货单位补全*/
    autoCompleteFirm();
    function autoCompleteFirm(inputId){
        var url="${ctx}/drug/drugStorageDept/findByMasterClass";
        $("#supplier").autocomplete(url, {
            minChars: 0, //在触发autoComplete前用户至少需要输入的字符数.
            max: 20,//autoComplete下拉显示项目的个数
            autoFill: false, //要不要在用户选择时自动将用户当前鼠标所在的值填入到input框
            //mustMatch: true, //autoComplete只会允许匹配的结果出现在输入框,所有当用户输入的是非法字符时将会得不到下拉框
            matchContains: true, //决定比较时是否要在字符串内部查看匹配,如ba是否与foo bar中的ba匹配.使用缓存时比较重要.不要和autofill混用
            multipleSeparator: '',//如果是多选时,用来分开各个选择的字符.
            multiple: false, //是否允许输入多个值即多次使用autoComplete以输入多个值
            scrollHeight: 300,
            width: "20%",
            dataType: 'json',
            method: 'POST',
            onBegin: function(options) { //修改--用于动态改变ledger的值
                options.extraParams.masterClass= $('#masterClassId').val();
                return options;
            },
            parse:  function(data){
                var rows = [];
                for(var i=0; i<data.length; i++){
                    rows[rows.length] = {
                        data:data[i],
                        value:data[i].id,
                        result:data[i].storageName
                    };
                }
                return rows;
            }, formatItem: function(data, i, max){
                return data.storageName;
            }
        }).result(function(event,data,formatted){
            $('#storageFrom').attr('value',data.id);
        });
    }
    loadSupplier();
    function loadSupplier() {
        $("#supplierOut").html("");
        var exportClass = $('#masterClass').val();  //出库类别
        $.ajax({
            url: '${ctx}/drug/drugExport/getSupplierList?type=' + exportClass,
            type: 'get',
            contentType: 'application/json',
            async: true,
            success: function (data, textStatus, jqXHR) {
                if (data.length > 0) {
                    if(typeof(data[0].supplierJc) == 'undefined'){
                        $.each(data, function (index, item) {
                            $("#supplierOut").append("<option value='" + item.storageCode + "'>" + item.storageName + "</option>");
                        });
                    }else{
                        $.each(data, function (index, item) {
                            $("#supplierOut").append("<option value='" + item.id + "'>" + item.supplierJc + "</option>");
                        });
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }
    //弹出右边增加药品框
   /* function addDrugList(){
        $("#stcokLeftDiv").attr("class","main-content col-lg-8");
        $("#stcokRightDiv").show('normal');
        return loadDiv('rigthCenterDiv','${ctx}/drug/drugStock/form');
        $("#remarks").attr("readonly","false");
        $("#minUnits_change").css("display","none");
        $("#packageUnits_change").css("display","none");
        $("#packageUnits_add").show('normal');
        $("#minUnits_add").show('normal');
    }
*/
    //弹出右边增加药品明细框
    function addDrugList(){
        $("#drugInOutDiv").attr("class","main-content col-lg-8");
        $("#drugInOutRightDiv").show('normal');
        return loadDiv('rigthCenterDiv','${ctx}/drug/drugStock/drugInOutForm');
    }
    //删除一行药品
    function removeList(btn){
        var price=parseFloat($('#totalMoney').val());
        var td = $(btn).parent().parent().children().eq(0).text();
        $(btn).parent().parent().remove();
        var obj=$.parseJSON(td);
        var total = parseFloat(parseFloat(price,10)-parseFloat(obj.purchasePrice,10)*parseInt(obj.quantityIn,10));
        total = Math.round(parseFloat(total)* 100) / 100;
        $('#totalMoney').val(total);
    }

    //修改药品
    function updateList(btn){
        var price=parseFloat($('#totalMoney').val());
        var td = $(btn).parent().parent().children().eq(0).text();
        $("#drugInOutDiv").attr("class","main-content col-lg-8");
        $("#drugInOutRightDiv").show('normal');
        fillForm($("#inputForm"),td);
        $(btn).parent().parent().remove();
        var obj=$.parseJSON(td);
        var total = parseFloat(price,10)-parseFloat(obj.purchasePrice,10)*parseInt(obj.quantityIn,10);
        total = Math.round(parseFloat(total)* 100) / 100;
        $('#totalMoney').val(total);
    }
    //自动填充合计金额
    function totalPrice(json){
        var obj=$.parseJSON(json);
        var list=$("table tr").find("td:eq(13)");
        var price=0;
        for (var i=0;i<list.length;i++){
            price+=parseFloat(list[i].innerText);
        }
        $('#totalMoney').val(price);
    }
    //设置出库日期为当前时间,不能编辑
    var date = new Date();
    var nowMonth = "";
    if(date.getMonth()+1 <= 9){
        nowMonth = "0" + (date.getMonth() + 1) + "";
    }else{
        nowMonth = (date.getMonth() + 1) + "";
    }
    var hours = "";
    if(date.getHours() < 10){
        hours = "0" + date.getHours();
    }else{
        hours = date.getHours();
    }
    var minutes = "";
    if(date.getMinutes() < 10){
        minutes = "0" + date.getMinutes();
    }else{
        minutes = date.getMinutes();
    }
    var seconds = "";
    if(date.getSeconds() < 10){
        seconds = "0" + date.getSeconds();
    }else{
        seconds = date.getSeconds();
    }
    var now = date.getFullYear() + "-" + nowMonth + "-" + date.getDate() + " " + hours + ":" + minutes + ":" + seconds;
    $('#expireDate').val(now);
    //金额总计
    $('#totalMoney').val(0.00);
    //保存
    function saveImport(){
        var masterClassId = $("#masterClassId").val();  //入库类别
        var storageFrom= $('#storageFrom').val();//供货单位
        var exportClass = $("#masterClass").val();  //出库类别
        var receiver = $('#supplierOut').val();     //收货科室
        var expireDate = $('#expireDate').val();  //日期
        var totalMoney = $('#totalMoney').val();  //合计
        if(storageFrom==null ||storageFrom==""){
            toastr.error('请选择供货单位');
            return ;
        }
        if(receiver==null ||receiver==""){
            toastr.error('请选择收货科室');
            return ;
        }else{
            var list=$("table tr").find("td:eq(0)");
            var dataList=[];
            var data={};
            if(list.length > 0){
            for (var i=0;i<list.length;i++){
//            data=$.parseJSON( list[i].innerText );

                data=jQuery.parseJSON( list[i].innerText );
                console.log(data);
                data.storageFrom=$('#storageFrom').val();//供货单位
                data.importClass=$('#masterClassId').val(); //入库类别
                data.exportClass = $("#masterClass").val();  //出库类别
                data.receiver = $('#supplierOut').val();     //收货单位
                data.expireDate = $('#expireDate').val();  //日期
                data.totalMoney = $('#totalMoney').val();
                console.log(data);
                data.supplier = data['supplier'];
                data.packageUnits=data['packageUnits'];
                data.drugName = data['drugName'];
                data.drugCode = data['drugCode'];
//            drugStock.discount = data.discount;
                data.infoId = data['infoId'];
                //data.documentNo = data['documentNo'];
                //drugStock.quantity = data['drugStock.quantity'];
                //data.drugStock = drugStock;
                //var drugPrice = {};
                data.drugInfo = data['infoId'];
                data.retailPrice = data['retailPrice'];//零售价
                data.purchasePrice = data['purchasePrice'];//进货价
                data.quantity = data['quantity'];//当前库存
                data.quantityIn = data['quantityIn'];//入库数量
                data.quantityOut = data['quantityIn'];//出库数量

                data.receiver = receiver;
                data.exportClass = exportClass;
                data.documentNo = "ZYCK201703200001";

                dataList.push(data);
            }


            var dataListJson = JSON.stringify(dataList);
            if(dataListJson==null ||dataListJson==""){
                toastr.error('请添加要入库的药品');
            }else{
                $.ajax({
                    type: "POST",
                    //url: '${ctx}/drug/drugStock/importDrug',
                    url: '${ctx}/drug/drugStock/saveInOutDrug',
                    data:dataListJson,
                    'contentType': 'application/json',
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        if (data.code == 'success') {
                            toastr.success('对消入出库保存成功!');
                            return loadDiv('mainCenterDiv', '${ctx}/drug/drugStock/drugInOutIndex');
                        } else if (data.code == 'no') {
                            toastr.error('当前科室不存在库房，无法进行该操作！');
                        }
                        else {
                            toastr.error('网络连接错误,请检查网络');
                        }
                    },
                    error: function (data) {
                        toastr.error('网络连接错误,请检查网络');
                    }
                });
            }
        } else {
            toastr.error('没有数据保存!');
            return false;
        }
        }
    }


</script>